import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Popover,
  Empty,
  Select,

  Checkbox, Tooltip, BackTop, TreeSelect, Descriptions,
} from 'antd';
import { popoverPrice,renderValveOpen } from '@/utils/utils';
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import request from '@/utils/request';
import './index.less';
import ReactEcharts from 'echarts-for-react';
import { routerRedux } from 'dva/router';

const { Option } = Select;
const FormItem = Form.Item;

@connect(({ level_user_billings, loading, global, owner }) => ({
  level_user_billings,
  global,
  owner,
  loading: loading.models.level_user_billings,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      data: [],
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      maxWidth: 200,
      all_users: [],
    };

  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      level_user_billings: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.ant-table-body');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {

      const {
        level_user_billings: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'level_user_billings/changeTableY',
      });
      dispatch({
        type: 'level_user_billings/changeLoaded',
      });
      return;
      dispatch({
        type: 'level_user_billings/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'level_user_billings/changeLoaded',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    this.setState({
      maxWidth: document.querySelector('.table-page').offsetWidth - 20,
    }, function() {
      console.log('maxWidth', this.state.maxWidth);
    });


    const that = this;
    request(`/all_regions`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
        });
      }

    });

  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'level_user_billings/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    dispatch({
      type: 'level_user_billings/changeTableY',
    });
  };


  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'level_user_billings/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        const table = document.querySelector('.ant-table-body');
        if (table) {
          setTimeout(() => {
            table.scrollTop = 0;
          }, 0);
        }

        if (cb) cb();
      },
    });
  };
  keyPress = (e) => {
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press');
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        this.searchFunc();
      });
    }
  };
  searchFunc = () => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      console.log(fieldsValue);
      if (!fieldsValue.name && !fieldsValue.mobile && !fieldsValue.meter_number) {
        message.error('请输入户主姓名，户主手机或水表号');
        return;
      }
      request(`/accounts`, {
        method: 'GET',
        params: {
          ...fieldsValue,
          per_page: 1,
        },
      }).then((response) => {
        if (response.status === 200 && response.data.data.length >= 1) {
          this.props.dispatch({
            type: 'level_user_billings/saveDetailData',
            payload: response.data.data[0],
            callback:()=>{
              this.handleSearch({
                ...fieldsValue,
                account_id: response.data.data[0].id,
              });
            }
          });

        }else{
          message.error('没有找到用户，请检查输入条件');
        }
      });


    });
  };

  renderSimpleForm() {

    const {
      form: { getFieldDecorator },
      level_user_billings: { data,searchParams },
    } = this.props;
    let total=0;
    for (let i=0;i<data.length;i++){
      total+=Number(data[i].amount)
    }
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="户主姓名">
          {getFieldDecorator('name', {
            initialValue: searchParams.name,
          })(<Input style={{ width: '120px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="户主手机">
          {getFieldDecorator('mobile', {
            initialValue: searchParams.mobile,
          })(<Input style={{ width: '120px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('meter_number', {
            initialValue: searchParams.meter_number,
          })(<Input style={{ width: '150px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label={'年份'}>
          {getFieldDecorator('year', {
            initialValue: searchParams.year,
          })(
            <Select style={{ width: '150px' }} allowClear={false}>
              <Option value={'2017'}>2017年</Option>
              <Option value={'2018'}>2018年</Option>
              <Option value={'2019'}>2019年</Option>
              <Option value={'2020'}>2020年</Option>
              <Option value={'2021'}>2021年</Option>
            </Select>,
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              this.searchFunc();
            }}
          >
            查询
          </Button>
          <Button type={'primary'} className={'btn-cyan'} style={{ marginLeft: 8 }} icon='export' onClick={() => {
            message.info('功能正在开发中');
          }}>
            导出报表
          </Button>
        </FormItem>
        {
          total>0&&
          <FormItem>
            <h2 style={{marginBottom:'0'}}>当年扣费总金额 <span style={{color:'#f4a000'}}>{total.toFixed(2)}</span> 元</h2>
          </FormItem>
        }

      </Form>
    );
  }

  render() {
    const that = this;
    const {
      level_user_billings: { data, loading, tableY, detailData, summary, selectedRowKeys, additional },
      global: { gridTableW },
    } = this.props;
    const columns = [
      {
        title: '扣费日期',
        dataIndex: 'date',
      },
      {
        title: '用水性质',
        dataIndex: 'price_nature',
        render: (value, row) => {
          return  <Popover title={value.name} content={popoverPrice(value)}><span style={{
            overflow:'hidden',
            textOverflow: 'ellipsis',
            whiteSpace:'nowrap',
            display:'inline-block',
          }}>{`${value.name}`}</span></Popover>;
        },
      },
      {
        title: '所属阶梯',
        dataIndex: 'level',
        render: (value, row) => {
          return `阶梯${value}`;
        },
      },
      {
        title: '水表读值',
        dataIndex: 'current_billing_value',
      },
      {
        title: <Tooltip title={`有'/'表示当前阶梯包含前一阶梯扣费水量`}><span>扣费水量 <Icon type="question-circle"/></span></Tooltip>,
        dataIndex: 'level_one_consumption',
        render: (value, row) => {
          if (row.level === 1) {
            return row.level_one_consumption;
          } else if (row.level === 2) {
            if (Number(row.level_one_consumption) !== 0) {
              return `${row.level_one_consumption} / ${row.level_two_consumption}`;
            }
            return row.level_two_consumption;
          } else if (row.level === 3) {
            if (Number(row.level_one_consumption) !== 0) {
              return `${row.level_one_consumption} / ${row.level_two_consumption} / ${row.level_three_consumption}`;
            }
            if (Number(row.level_two_consumption) !== 0) {
              return `${row.level_two_consumption} / ${row.level_three_consumption}`;
            }
            return row.level_three_consumption;
          }

        },
      },
      {
        title: <Tooltip title={`有'/'表示当前阶梯包含前一阶梯扣费水量`}><span>阶梯价格 <Icon type="question-circle"/></span></Tooltip>,
        dataIndex: 'level_one_price',
        render: (value, row) => {
          if (row.level === 1) {
            return row.price_nature.level_one_price;
          } else if (row.level === 2) {
            if (Number(row.level_one_consumption) !== 0) {
              return `${row.price_nature.level_one_price} / ${row.price_nature.level_two_price}`;
            }
            return row.price_nature.level_two_price;
          } else if (row.level === 3) {
            if (Number(row.level_one_consumption) !== 0) {
              return `${row.price_nature.level_one_price} / ${row.price_nature.level_two_price} / ${row.price_nature.level_three_price}`;
            }
            if (Number(row.level_two_consumption) !== 0) {
              return `${row.price_nature.level_two_price} / ${row.price_nature.level_three_price}`;
            }
            return row.price_nature.level_three_price;
          }
        },
      },
      {
        title: <Tooltip title={`有'/'表示当前阶梯包含前一阶梯扣费水量`}><span>水费 <Icon type="question-circle"/></span></Tooltip>,
        dataIndex: 'level_three_fee',
        render: (value, row) => {
          if (row.level === 1) {
            return row.level_one_fee;
          } else if (row.level === 2) {
            if (Number(row.level_one_consumption) !== 0) {
              return `${row.level_one_fee} / ${row.level_two_fee}`;
            }
            return row.level_two_fee;
          } else if (row.level === 3) {
            if (Number(row.level_one_consumption) !== 0) {
              return `${row.level_one_fee} / ${row.level_two_fee} / ${row.level_three_fee}`;
            }
            if (Number(row.level_two_consumption) !== 0) {
              return `${row.level_two_fee} / ${row.level_three_fee}`;
            }
            return row.level_three_fee;
          }
        },
      },
      {
        title: <Tooltip title={`有'/'表示当前阶梯包含前一阶梯扣费水量`}><span>阶梯污水处理费 <Icon type="question-circle"/></span></Tooltip>,
        dataIndex: 'level_three_fee2',
        render: (value, row) => {
          if (row.level === 1) {
            return row.price_nature.level_one_sewage_price;
          } else if (row.level === 2) {
            if (Number(row.level_one_consumption) !== 0) {
              return `${row.price_nature.level_one_sewage_price} / ${row.price_nature.level_two_sewage_price}`;
            }
            return row.price_nature.level_two_sewage_price;
          } else if (row.level === 3) {
            if (Number(row.level_one_consumption) !== 0) {
              return `${row.price_nature.level_one_sewage_price} / ${row.price_nature.level_two_sewage_price} / ${row.price_nature.level_three_sewage_price}`;
            }
            if (Number(row.level_two_consumption) !== 0) {
              return `${row.price_nature.level_two_sewage_price} / ${row.price_nature.level_three_sewage_price}`;
            }
            return row.price_nature.level_three_sewage_price;
          }

        },
      },
      {
        title: <Tooltip title={`有'/'表示当前阶梯包含前一阶梯扣费水量`}><span>污水处理费 <Icon type="question-circle"/></span></Tooltip>,
        dataIndex: 'level_one_sewage_fee',
        render: (value, row) => {
          if (row.level === 1) {
            return row.level_one_sewage_fee;
          } else if (row.level === 2) {
            if (Number(row.level_one_consumption) !== 0) {
              return `${row.level_one_sewage_fee} / ${row.level_two_sewage_fee}`;
            }
            return row.level_two_sewage_fee;
          } else if (row.level === 3) {
            if (Number(row.level_one_consumption) !== 0) {
              return `${row.level_one_sewage_fee} / ${row.level_two_sewage_fee} / ${row.level_three_sewage_fee}`;
            }
            if (Number(row.level_two_consumption) !== 0) {
              return `${row.level_two_sewage_fee} / ${row.level_three_sewage_fee}`;
            }
            return row.level_three_sewage_fee;
          }

        },
      },
      {
        title: '总金额',
        dataIndex: 'amount',
      },
    ];
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>户主扣费报表</span>
      </div>
      <div className="table-page">
        <div className="table-condition">
          {this.renderSimpleForm()}
        </div>
        <div >
          <div >
            <Descriptions title={''} bordered     column={{ xxl: 4, xl: 4, lg: 4, md: 4, sm: 4, xs: 4 }}>
              <Descriptions.Item label="户主姓名" span={1}><Tooltip
                title={detailData.name}>{detailData.name}</Tooltip></Descriptions.Item>
              <Descriptions.Item label="户主手机" span={1}><Tooltip
                title={detailData.mobile}>{detailData.mobile}</Tooltip></Descriptions.Item>
              <Descriptions.Item label="户主地址" span={1}><Tooltip
                title={detailData.address}>{detailData.address}</Tooltip></Descriptions.Item>
              <Descriptions.Item label="水表号" span={1}><Tooltip
                title={detailData.meter_number}>{detailData.meter_number}</Tooltip></Descriptions.Item>
              <Descriptions.Item label="当前用水性质" span={1}><Tooltip
                title={detailData.price_nature&&detailData.price_nature.name}>{detailData.price_nature&&detailData.price_nature.name}</Tooltip></Descriptions.Item>
              <Descriptions.Item label="累计缴费金额"  span={1}>{detailData.cumulative_payment_amount}</Descriptions.Item>
              <Descriptions.Item label="当前余额"  span={1}>{detailData.valve_status?<p className={Number(detailData.balance)>=Number(detailData.balance_alarm_amount)?
                'table-success table-status':
                Number(detailData.balance) > 0?'table-warm table-status':'table-error table-status' }>{detailData.balance}</p>:''}</Descriptions.Item>
              <Descriptions.Item label="阀门状态"  span={1}>{detailData.valve_status?renderValveOpen(detailData.valve_status):''}</Descriptions.Item>
            </Descriptions>
          </div>
          <div style={{ flex: 1 }}>
            <Table
              style={{ color: '#fff', borderBottom: '1px solid #e8e8e8' }}
              className="custom-small-table meter-table vendor-meter"
              rowKey={'id'}
              loading={loading}
              dataSource={data}
              columns={columns}
              pagination={false}
              locale={{
                emptyText:detailData.name?<Empty description={'暂无数据'} />:<Empty description={'请输入条件进行查询'} />
              }}
              scroll={{ x: true, y: tableY }}
              size="small"
              rowClassName={(row, index) => {
                return `level_${row.level}`;
              }}
            />
          </div>
        </div>
        <BackTop target={() => {
          return document.querySelector('.ant-table-body');
        }}/>
      </div>
    </div>;
  }
}

export default BasicList;
